package kadledav.backend.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import kadledav.backend.dao.NewsDAO;
import kadledav.backend.dto.NewsDTO;
import kadledav.backend.model.News;
import kadledav.backend.service.NewsService;

@Service
@Transactional
public class NewsServiceImpl implements NewsService {

	Logger logger = Logger.getLogger(NewsServiceImpl.class);

	@Autowired
	NewsDAO newsDao;

	public List<NewsDTO> getAllNews() {
		return boToDTO(newsDao.getAll());
	}

	public List<NewsDTO> getNewsByDateDesc(int limit) {
		return boToDTO(newsDao.getOrderByDateDesc(limit));
	}

	private List<NewsDTO> boToDTO(List<News> all) {
		List<NewsDTO> allDTO = new ArrayList<NewsDTO>(all.size());
		for (News news : all) {
			allDTO.add(news.toDTO());
		}
		return allDTO;
	}


	public void addNews(NewsDTO newOne) {
		if (newOne.getMessage() == null || newOne.getMessage().trim().isEmpty()) {
			return;
		}
		News news = new News();
		news.fromDTO(newOne);
		logger.debug("DAO start inserting: " + news.getMessage());
		newsDao.insert(news);
		logger.debug("DAO inserted: " + news.getMessage() + " with id " + news.getId());

	}

	public NewsDTO findById(Integer id) {
		return newsDao.findById(id).toDTO();
	}

}
